<?php
// +----------------------------------------------------------------------
// | zhanshop-php / FileService.php    [ 2025/1/13 13:38 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\index\v1\service;

use Qiniu\Auth as SdkAuth;
use zhanshop\App;
use zhanshop\server\Request;
use zhanshop\server\Response;

class FileService
{
    /**
     * 获取七牛的上传token
     * @param string $type
     * @param array|null $policy
     * @return array
     * @throws \Exception
     */
    public function uploadToken(string $type, ?array $policy = null)
    {
        App::phar()->import('extend/library/qiniu');
        $accesskey = App::config()->get('sns.qiniu.accesskey');
        $secretKey = App::config()->get('sns.qiniu.secretkey');
        $buckets = App::config()->get('sns.qiniu.buckets');
        $bucket = $buckets[$type] ?? App::error()->setError($type.'存储空间未配置', 404);
        $auth = new SdkAuth($accesskey, $secretKey);
        return [
            'token' => $auth->uploadToken($bucket['bucket'], null, 600, $policy),// 让token的有效期只有10分钟
            'domain' => $bucket['domain'],
            'bucket' => $bucket['bucket'],
            'policy' => $policy,
            'expires' => 600
        ];
    }
    /**
     * 七牛的上传回调
     * @param string $type
     * @param array|null $policy
     * @return array
     * @throws \Exception
     */
    public function uploadcallback(array $param)
    {
        $inputKey = $param['inputKey'] ?? '';
        $items = $param['items'] ?? '';
        if($inputKey && $items){
            App::cache()->set('qiniu:upload:callback:'.$inputKey, json_encode($items), 600);
        }
    }

    /**
     * 查询上传回调结果
     * @param string $inputKey
     * @param int $timeout
     * @return array
     * @throws \RedisException
     */
    public function uploadcallbackResult(string $inputKey, int $timeout = 30)
    {
        $startTime = microtime(true);
        $cacheKey = 'qiniu:upload:callback:'.$inputKey;
        while (true){
            $result = App::cache()->get($cacheKey);
            if($result != false){
                $result = json_decode($result, true);
                break;
            }
            if((microtime(true) - $startTime) > $timeout) break;
            usleep(500000);
        }
        return ['result' => $result];
    }
}